package com.chuangjiangx.member.manager.client.web.score.controller;

import com.chuangjiangx.commons.BeanUtils;
import com.chuangjiangx.commons.page.PagingResult;
import com.chuangjiangx.commons.response.CamelResponse;
import com.chuangjiangx.commons.response.Response;
import com.chuangjiangx.commons.response.ResponseUtils;
import com.chuangjiangx.commons.response.UnderlineResponse;
import com.chuangjiangx.member.basic.ddd.application.MemberApplication;
import com.chuangjiangx.member.basic.ddd.dal.dto.MbrAccountDTO;
import com.chuangjiangx.member.basic.ddd.query.MbrAccountQuery;
import com.chuangjiangx.member.basic.ddd.query.MemberQuery;
import com.chuangjiangx.member.basic.ddd.query.dto.MemberDTO;
import com.chuangjiangx.member.manager.basic.web.controller.BaseController;
import com.chuangjiangx.member.manager.basic.web.interceptor.Login;
import com.chuangjiangx.member.manager.basic.web.interceptor.Permissions;
import com.chuangjiangx.member.manager.client.web.score.request.ConvertGiftRequest;
import com.chuangjiangx.member.manager.client.web.score.response.GiftMemberRespose;
import com.chuangjiangx.member.manager.client.web.score.response.NewGiftListResponse;
import com.chuangjiangx.member.manager.client.web.score.response.NewGiftsListDTOResponse;
import com.chuangjiangx.member.manager.common.Constants;
import com.chuangjiangx.member.manager.common.ThreadLocalUser;
import com.chuangjiangx.member.score.ddd.application.command.ExchangeGoodsCommand;
import com.chuangjiangx.member.score.ddd.dal.condition.QueryScoreGiftRuleCondition;
import com.chuangjiangx.member.score.ddd.dal.dto.MbrScoreGiftRuleDetail;
import com.chuangjiangx.member.score.ddd.dal.dto.MemberScoreGiftRuleList;
import com.chuangjiangx.member.score.ddd.query.MbrScoreGiftRuleQuery;
import com.sun.jmx.snmp.ThreadContext;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 积分商城
 */
@RestController
@Api(value = "积分商城",tags = "积分")
@RequestMapping(value = "/app/member/store", produces = "application/json")
public class MbrScoreShopController extends BaseController {
    @Autowired
    private  MbrScoreGiftRuleQuery mbrScoreGiftRuleQuery;
    @Autowired
    private  MemberApplication memberApplication;
    @Autowired
    private MemberQuery memberQuery;
    @Autowired
    private MbrAccountQuery mbrAccountQuery;

    /**
     * 兑换商品列表
     *
     * @return 商品列表
     * @map data
     */
    @ApiOperation(value = "兑换商品列表")
    @RequestMapping(value = "/searchGoodsList",method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    @Login
    @Permissions("59006")
    public UnderlineResponse<NewGiftListResponse> searchGoodsList(@ApiParam(value = "手机号") String phone) throws Exception {

        ThreadLocalUser user = (ThreadLocalUser) ThreadContext.get(Constants.CURRENT_LOGIN_USER_KEY);
        NewGiftListResponse response = new NewGiftListResponse();
        QueryScoreGiftRuleCondition condition = new QueryScoreGiftRuleCondition();
        condition.setMerchantId(user.getMerchantId());
        condition.setStatus(1);
        //app貌似没有分页
        condition.setPageSize(100);
        PagingResult<MemberScoreGiftRuleList> pagingResult = mbrScoreGiftRuleQuery.findMbrScoreGiftRuleList(condition);
        if(pagingResult.getTotal() >0 ){
            List<NewGiftsListDTOResponse> newGiftsListDTOResponses = BeanUtils.convertCollection(pagingResult.getItems(), NewGiftsListDTOResponse.class, (e, t) -> {
                t.setOverConvertCount(e.getTotalGiftLimit() - e.getCount().intValue());
            });
            response.setGiftsListDTOs(newGiftsListDTOResponses);
        }
        //设置会员信息
        if (StringUtils.isNotBlank(phone)) {
            MemberDTO memberDTO = memberQuery.queryByMerchantAndMobile(user.getMerchantId(), phone);
            if(null != memberDTO){
                GiftMemberRespose giftMemberRespose = new GiftMemberRespose();
                giftMemberRespose.setId(memberDTO.getId());
                giftMemberRespose.setName(memberDTO.getName());
                giftMemberRespose.setMobile(memberDTO.getMobile());
                MbrAccountDTO mbrAccountDTO = mbrAccountQuery.queryBymemberId(memberDTO.getId());
                giftMemberRespose.setAvailableScore(mbrAccountDTO.getAvailableScore());
                response.setMemberDetail(giftMemberRespose);
            }
        }

        return (UnderlineResponse<NewGiftListResponse> )ResponseUtils.success(response);

    }

    /**
     * 兑换积分商品
     *
     * @param convertGiftRequest 商品id,会员手机号码
     * @return 兑换结果
     */
    @RequestMapping(value = "/convertGift",method = RequestMethod.POST)
    @ResponseBody
    @Login
    @Permissions("59007")
    @ApiOperation(value = "兑换积分商品")
    public Response convertGift(@Validated @RequestBody ConvertGiftRequest convertGiftRequest) throws Exception {

        ThreadLocalUser user = (ThreadLocalUser) ThreadContext.get(Constants.CURRENT_LOGIN_USER_KEY);
        //兑换商品所需参数
        ExchangeGoodsCommand command = new ExchangeGoodsCommand();

        command.setMerchantId(user.getMerchantId());
        command.setMerchantUserId(user.getMerchantUserId());
        command.setMemberId(convertGiftRequest.getMemberId());
        command.setScoreGiftRuleId(convertGiftRequest.getScoreGiftId());
        command.setStoreId(user.getStoreId());
        command.setStoreUserId(user.getStoreUserId());

        //兑换操作
        memberApplication.exchangeGoods(command);
        return ResponseUtils.success();
    }


    /**
     * 查询积分兑换规则详情
     * @param id
     * @return
     */
    @RequestMapping(value = "/detail/{id}",method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    @Login
    @ApiOperation(value = "查询积分兑换规则详情")
    public CamelResponse<MbrScoreGiftRuleDetail> detail(@PathVariable Long id){
        ThreadLocalUser user = (ThreadLocalUser) ThreadContext.get(Constants.CURRENT_LOGIN_USER_KEY);

        MbrScoreGiftRuleDetail de = mbrScoreGiftRuleQuery.findByIdAndMerchantId(id, user.getMerchantId());
        return (CamelResponse<MbrScoreGiftRuleDetail> )ResponseUtils.successCamel(de);
    }
}
